package com.itheima.ydd.controller;

import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sys_role")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private ISysUserService sysUserService;

    @GetMapping("/list") //角色列表分页page
    public ResultData list(Integer page, Integer limit, String name ){
        log.info("page={},pageSize={}",page,limit,name);

        //构造分页构造器
        Page pageInfo = new Page(page,limit);

        //构造条件构造器
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(name),SysRole::getName,name);

        //添加查询条件
        queryWrapper.orderByDesc(SysRole::getUpdateDate);
        //执行查询
        sysRoleService.page(pageInfo, queryWrapper);

        //封装对象
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", pageInfo.getRecords());
        map.put("count", pageInfo.getTotal());
        map.put("totalPages", pageInfo.getSize());
        map.put("pageSize", limit);
        map.put("currentPage", pageInfo.getCurrent());
        return ResultData.ok("",map);

    }
    //
    @PostMapping("/update")  //角色修改
    public R<String> update(@RequestBody SysRoleDto sysRoleDto){
        log.info("修改角色信息:{}",sysRoleDto.toString());

        //将sysRoleDto拷贝到sysRoleDto
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDto, sysRole);

        //获取角色的菜单id
        List<String> menuIds = sysRoleDto.getMenuids();
        //获取角色所拥有的的菜单id
        String sysRoleId = sysRoleDto.getId();

        //创建条件构造器
        LambdaQueryWrapper<SysRoleMenu> sysRoleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleMenuLambdaQueryWrapper.eq(SysRoleMenu::getRoleId,sysRoleId);

        //删除原始信息
        sysRoleMenuService.remove(sysRoleMenuLambdaQueryWrapper);

        //重新添加遍历的菜单id
        for (String menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(sysRoleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.save(sysRoleMenu);
        }

        return R.success("修改成功","");
    }


/*    @GetMapping("/rowInfo")  //角色详情getById
    public ResultData rowInfo(String id){
        log.info("根据id查询角色详情");
        //通过id找到角色对象
        SysRole role = sysRoleService.getById(id);
        //创建sysRoleDto对象，并将role对象的信息复制到sysRoleDto中
        SysRoleDto sysRoleDto = new SysRoleDto();
        BeanUtils.copyProperties(role, sysRoleDto);
        //条件构造器
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        //在sys_role_menu表中匹配role_id
        queryWrapper.eq(SysRoleMenu::getRoleId, role.getId());
        //创建集合容器用于存储
        List<SysMeauDto> sysMenuDtos = new ArrayList<>();

        List<SysRoleMenu> list = sysRoleMenuService.list(queryWrapper);
        //创建children集合
        SysMeauDto sysMenu = new SysMeauDto();
        for (SysRoleMenu sysRoleMenu : list) {
            SysMenu menu = sysMenuService.getById(Integer.parseInt(sysRoleMenu.getMenuId()));
            BeanUtils.copyProperties(menu, sysMenu);

            sysMenuService.list();
            sysMenuDtos.add(sysMenu);
        }
        sysRoleDto.setAuthList(sysMenuDtos);
        return ResultData.ok("",sysRoleDto);



    }*/
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
    SysRoleDto roleDto = sysRoleService.rowInfo(id);
    return ResultData.ok("",roleDto);
}

    @GetMapping("/allData")   //角色列表-全部getAll
    public ResultData allData(){
        List<SysRole> list = sysRoleService.list();
/*        for (SysRole sysRole : list) {
            System.out.println(sysRole.toString());
        }*/
        return ResultData.ok("",list);


    }
    @PostMapping("/add")  //角色添加
    public R<String> add(@RequestBody SysRoleDto sysRoleDto){
        log.info("新增角色，角色信息:{}",sysRoleDto.toString());

        sysRoleDto.setCreateDate(LocalDateTime.now());
        sysRoleDto.setUpdateDate(LocalDateTime.now());

        sysRoleService.save(sysRoleDto);
        //获取添加后的id
        String id = sysRoleDto.getId();
        List<String> menuIds = sysRoleDto.getMenuids();
        //遍历菜单id，进行存储
        for (String menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(id);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.save(sysRoleMenu);
        }
        return R.success("添加成功","");

    }

    @GetMapping("/del")  //角色删除
    public R<String> del(String id){
        log.info("删除管理员，id为：{}",id);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getRoleId,id);
        int count = sysUserService.count(queryWrapper);
        if(count > 0){
            throw new BusinessException("该角色下有用户,不能删除");
        }
        sysRoleService.removeById(id);

        return R.success("删除成功","");
    }

}



